import { DefaultService as Api, DefaultService } from '@/servers';
import { IObject, StaticMethodNames } from '../dynamic-table/helper';
import { onMounted } from 'vue';
import { modelFormItemsProps } from './form';
import { getValue } from '@/utils/get';

type MultiperOptions = {
  url: string | string[];
  params: any[][];
  mapper: string[][]; // [ 列表位置，keyProp, valueProp, title ]
  options: { title: string; options: { label: string; value: string }[] }[];
  form: any;
  labelMapper: IObject[];
};

export type MultiperOptionsResult = MultiperOptions & {
  getOptions: () => void;
};

export const useOptions = (schema: Partial<MultiperOptions>, isInit = true) => {
  const urls = Array.isArray(schema.url) ? schema.url : [schema.url];
  const params = schema.params || [];
  const mapper = schema.mapper || [];

  const state = schema as MultiperOptionsResult;

  const getOptions = async () => {
    const res = await Promise.all(urls.map((item, index) => Api[item as any](...(params[index] || []))));
    state.options = mapper.map(([url, keyProp, valueProp, title], index) => {
      const list = getValue(res[index], url);
      const options = list.map((item: any) => ({
        label: item[keyProp],
        value: item[valueProp]
      }));

      return { title: title || '--', options };
    });

    state.labelMapper = mapper.map(([url, keyProp, valueProp], index) => {
      const list = getValue(res[index], url);
      const result = list.reduce((pre: any, item: any) => {
        pre[item[valueProp]] = item[keyProp];
        return pre;
      }, {});

      return result;
    });
  };

  state.getOptions = getOptions;

  if (isInit) {
    onMounted(() => {
      getOptions();

      console.log(state);
    });
  }

  return state;
};

// 获取查询选项

/**
 * @description 获取查询选项
 * @param schema
 */
export const useQueryForm = (schema: Partial<SchemaOptions>, isInit = true) => {
  const defaultSchema: SchemaOptions = {
    formItems: [],
    loading: false,
    data: {}, // 接口结果
    url: '', // 接口地址
    queryParams: [
      // [ 属性名， 位置：？标识：？所匹配的标识值，选项对象/数组，？title ]
      ['prop', 'data.list:1', 'content'],
      ['prop2', 'data', 'countries', 't:标题名称']
    ],
    handleData: () => {}
  };

  // 这里的合并后应该返回 props⭐⭐⭐
  const mergeState = (options: IObject, props: IObject) => {
    Object.keys(options).forEach(key => !Reflect.has(props, key) && (props[key] = options[key]));
    return props;
  };

  const state = mergeState(defaultSchema, schema);

  const formatOptions = (obj: IObject, len: number) => {
    if (len === 1) {
      let label_key: string = '',
        value_key: string = '';

      return (
        Object.values(obj).map((item, index) => {
          !index &&
            Object.entries(item).forEach(([key, value]) => {
              if (typeof value === 'number') {
                value_key = key;
              } else if (typeof value === 'string') {
                label_key = key;
              }
            });

          return {
            label: item[label_key],
            value: item[value_key]
          };
        }) || []
      );
    }
    return Object.entries(obj).map(([key, value]) => {
      return {
        label: value,
        value: Number(key)
      };
    });
  };

  const fetchOptions = async () => {
    state.loading = true;
    // @ts-ignore
    const res = await Api[state.url as StaticMethodNames<typeof DefaultService>]();
    state.data = res.data;

    // 处理查询选项
    state.queryParams.forEach((item: any) => {
      const [prop, url, options, title] = item;
      const target = state.formItems.find((i: modelFormItemsProps) => i.prop === prop);
      const pos = url.split(':');
      const source = pos[1] ? getValue(res, pos[0])[pos[1]] : getValue(res, pos[0]);

      if (target) {
        target.options = formatOptions(source[options], pos.length);
        target.label = title || source.title;

        // console.log(title, source.title);
      }

      state.loading = false;
    });
  };

  if (isInit) {
    onMounted(() => {
      fetchOptions();
    });
  }

  return {
    fetchOptions,
    ...state
  };
};

type ParamsItem = [
  string, // 属性名
  string, // 位置：？标识：？所匹配的标识值
  string, // 选项对象/数组
  string? // ？title
];

export type SchemaOptions = {
  formItems: modelFormItemsProps[];
  data: any;
  url: string;
  queryParams: ParamsItem[];
  loading: boolean;
  handleData: (data: any, items: modelFormItemsProps[]) => void;
};

export interface SchemaResultOptions extends SchemaOptions {
  fetchOptions: () => void;
}

export const tt = () => {};
